package com.phkj.qdh.net

//import com.blankj.utilcode.util.EncryptUtils
import com.phkj.qdh.utils.LogUtil
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @ProjectName:    KotlinCoroutine
 * @Package:        com.blue.kotlincoroutine.net
 * @ClassName:      CommInterceptor
 * @Description:    http拦截器，添加公共参数
 * @Author:         BLUE
 * @CreateDate:     6/1/21 5:00 PM
 * @UpdateUser:     更新者
 * @UpdateDate:     6/1/21 5:00 PM
 * @UpdateRemark:   更新说明
 * @Version:        1.0
 */
class CommInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        val httpUrl = oldRequest.url
        val scheme = httpUrl.scheme
        val host = httpUrl.host
        val path = httpUrl.encodedPath

        //当满足某条件时，直接取消
        /*      if (SPStaticUtils.getString(STORE_ID, SP_NONE_STRING) == SP_NONE_STRING) {
                  if (oldRequest.url.toString().equals(Url.baseUrl + Url.LOGIN)||oldRequest.url.toString().contains("192.168.0.")) {
                  }else{
                      chain.call().cancel()
                  }
                  return chain.proceed(oldRequest)
              }
      */
        //添加公共参数
        if (oldRequest.method == "GET") {
            //加密的字段
            val sb = StringBuilder()
            //请求连接的key列表
            val queryList = httpUrl.queryParameterNames
            //简单排序
            val sort = queryList.sorted()
            sort.forEachIndexed { index, s ->
                if (!httpUrl.queryParameter(s).isNullOrBlank()) {
                    sb.append(s)
                    sb.append("=")
                    sb.append(httpUrl.queryParameter(s))
                    sb.append("&")
                }
            }
            if (sb.toString().isNotBlank()) {
                sb.deleteCharAt(sb.length - 1).toString()
            }
            //获取签名
//            val sign = getSign(sb.toString())
//            sb.append("&signed=$sign")
            //生成新的请求链接
            val newUrl = StringBuilder()
            newUrl.append(scheme).append("://").append(host).append(path).append("?")
                .append(sb.toString())
            LogUtil.E("geturl$newUrl")
            val builder = oldRequest.newBuilder().url(newUrl.toString())

            return chain.proceed(builder.build())
        }
        if (oldRequest.method == "POST") {
            if (oldRequest.body is FormBody) {
                val bodyBuilder = FormBody.Builder()
                val formBody = oldRequest.body as FormBody
                val map = HashMap<String, Any>()
                for (i in 0 until formBody.size) {
                    if (formBody.encodedValue(i).isNotBlank()) {
                        map[formBody.encodedName(i)] = formBody.encodedValue(i)
                        bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i))
                    }
                }
                val sort = map.keys.sorted()

                val sb = StringBuilder()

                sort.forEach {
                    sb.append(it)
                    sb.append("=")
                    sb.append(map[it])
                    sb.append("&")
                }
                if (sb.toString().isNotBlank()) {
                    sb.deleteCharAt(sb.length - 1).toString()
                }
//                val sign = getSign(sb.toString())
//                bodyBuilder.addEncoded("signed", sign)
                val request = oldRequest.newBuilder().post(bodyBuilder.build()).build()
                return chain.proceed(request)
            }
        }
        return chain.proceed(oldRequest)
    }

//    fun getSign(s: String): String {
//        LogUtil.E("加密字段${s + APP_KEY}")
//        return EncryptUtils.encryptMD5ToString(s + APP_KEY).lowercase()
//    }
}